import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Http, Headers } from "@angular/http";
import { ModelScheme } from "../entity/model-scheme.model"
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class ModelSchemeService {
  private readonly param = "modelSchemes";
  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) { }
  getModelSchemes() {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.json().data as ModelScheme[])
      .catch(this.handleError);
  }
  create(modelScheme: ModelScheme): Promise<ModelScheme> {
    return this.http
      .post(this.url, JSON.stringify(modelScheme))
      .toPromise()
      .then(res => res.json().data)
      .catch(this.handleError);
  }
  update(modelScheme: ModelScheme): Promise<boolean> {
    const url = `${this.url}`;
    return this.http
      .put(url, JSON.stringify(modelScheme))
      .toPromise()
      .then(response => {
        try {
          let result = response.json();
          switch (result.code) {
            case "200":
              return true;
            case "-1":
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }
  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(response => {
        try {
          let result = response.json();
          switch (result.code) {
            case "200":
              return true;
            case "-1":
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}



// WEBPACK FOOTER //
// ./src/app/service/model-scheme.service.ts